package com.cuitrip.business.location.map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.cuitrip.app.MainApplication;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.service.R;
import com.cuitrip.util.MapController;
import com.lab.app.BaseFragment;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.utils.LogHelper;

import java.util.HashMap;
import java.util.Map;

import io.rong.message.LocationMessage;

/**
 * Created by baziii on 15/8/18.
 */
public class GaoDeMapActivity extends CustomUiFragmentActivity {
    public static final String VALUE_LAT = "VALUE_LAT";
    public static final String VALUE_LNG = "VALUE_LNG";
    public static final String VALUE_NAME = "VALUE_NAME";
    public static final String IM_RESULT = "IM_RESULT";
    public static final int REQUEST = 14;
    public static final String SHOW_PLACE = "SHOW_PLACE";
    private boolean showPlace;

    public static void returnForIM(Context activity) {
        activity.startActivity(new Intent(activity, GaoDeMapActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra(IM_RESULT, true));
    }

    public static void startSearch(Activity activity, Intent intent) {
        activity.startActivityForResult(intent, REQUEST);
    }

    public static void startSearch(BaseFragment baseFragment,Intent intent){
        baseFragment.startActivityForResult(intent,REQUEST);

    }

    public static void startShow(Context context, double lat, double lng, String name) {
        context.startActivity(new Intent(context, GaoDeMapActivity.class)
                .putExtra(VALUE_LAT, lat).putExtra(VALUE_LNG, lng).putExtra(VALUE_NAME, name).putExtra(SHOW_PLACE, true));
    }

    public static double getLat(Intent intent) {
        return intent.getDoubleExtra(VALUE_LAT, 0);
    }

    public static double getLng(Intent intent) {
        return intent.getDoubleExtra(VALUE_LNG, 0);
    }

    public static String getName(Intent intent) {
        return intent.getStringExtra(VALUE_NAME);
    }

    double lat;
    double lng;
    String name;

    SearchView searchView;
    TextView titleView;
    TextView searchBtn;
    IconTextView backIcon;
    PickMapFragment pickMapFragment;
    MapListFragment mapListFragment;
    private PoiItem item;

    public void selectPoiItem(PoiItem item) {
        changFragment(true);
        pickMapFragment.changeCenter(item);
        showSearchView(false);
    }

    public void selectItem(PoiItem item) {
        this.item = item;
        if (item == null) {
            searchBtn.setText(R.string.operation_search);
            return;
        }
        searchBtn.setText(R.string.operation_ok_1);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //判断是否为展示地点
        showPlace = getIntent().getBooleanExtra(SHOW_PLACE, false);
        if (showPlace) {
            FrameLayout frameLayout = new FrameLayout(this);
            frameLayout.setId(R.id.content);
            setContentView(frameLayout);
            GaodeMapShowFragment fragment = new GaodeMapShowFragment();
            Bundle args = new Bundle();
            args.putDouble(VALUE_LAT, getIntent().getDoubleExtra(VALUE_LAT, 0));
            args.putDouble(VALUE_LNG, getIntent().getDoubleExtra(VALUE_LNG, 0));
            args.putString(VALUE_NAME, getIntent().getStringExtra(VALUE_NAME));
            fragment.setArguments(args);
            getSupportFragmentManager().beginTransaction().add(frameLayout.getId(), fragment).commit();
            return;
        }
        setContentView(R.layout.gaode_map);
        searchView = (SearchView) findViewById(R.id.searchView);
        backIcon = (IconTextView) findViewById(R.id.backIcon);
        backIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mapListFragment.isVisible()) {
                    changFragment(true);
                    showSearchView(false);
                } else {
                    setResult(RESULT_CANCELED);
                    finish();
                }
            }
        });
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                completeWord(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        titleView = (TextView) findViewById(R.id.titleView);
        searchBtn = (TextView) findViewById(R.id.searchBtn);
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断发送
                if (item != null) {
//                    Toast.makeText(GaoDeMapActivity.this, item.getTitle(), Toast.LENGTH_SHORT).show();
                    saveResult(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude(), item.getTitle());
                    return;
                }
                //如果searchView中有字
                String content = searchView.getQuery().toString();
                if (!TextUtils.isEmpty(content)) {
                    completeWord(content);
                    hideInputMethod();
                    return;
                }
                boolean showMap = searchView.getVisibility() == View.VISIBLE;
                showSearchView(!showMap);
                changFragment(!showMap);
            }
        });
        pickMapFragment = new PickMapFragment();
        mapListFragment = new MapListFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.mapContainer, pickMapFragment)
                .add(R.id.mapContainer, mapListFragment).show(pickMapFragment).hide(mapListFragment).commit();
        getSupportFragmentManager().executePendingTransactions();
        searchView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (readIntent()) {
                    pickMapFragment.move(lat, lng);
                } else {
                    pickMapFragment.showMyLocation();
                }
            }
        }, 300);

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (showPlace) {
                finish();
                return true;
            }
            if (mapListFragment.isVisible()) {
                changFragment(true);
                showSearchView(false);
            } else {
                setResult(RESULT_CANCELED);
                finish();
            }
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    public boolean readIntent() {
        if (getIntent().hasExtra(VALUE_LAT) &&
                getIntent().hasExtra(VALUE_LNG) && getIntent().hasExtra(VALUE_NAME)) {
            lat = getIntent().getDoubleExtra(VALUE_LAT, 0);
            lng = getIntent().getDoubleExtra(VALUE_LNG, 0);
            name = getIntent().getStringExtra(VALUE_NAME);
            return true;
        }
        return false;
    }

    private void showSearchView(boolean showSearchView) {
        titleView.setVisibility(!showSearchView ? View.VISIBLE : View.INVISIBLE);
        searchView.setVisibility(showSearchView ? View.VISIBLE : View.INVISIBLE);
        if (!showSearchView) {
            searchView.onActionViewCollapsed();
        } else {
            searchView.onActionViewExpanded();
        }
    }

    private void hideInputMethod() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
//如果开启
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
//关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
        }
    }

    private void changFragment(boolean showMap) {
        getSupportFragmentManager().beginTransaction()
                .hide(!showMap ? pickMapFragment : mapListFragment)
                .show(showMap ? pickMapFragment : mapListFragment).commit();
        getSupportFragmentManager().executePendingTransactions();
    }

    private void completeWord(String search) {
        mapListFragment.search(search);
        changFragment(false);
    }

    @Override
    public void onBackPressed() {
        if (!TextUtils.isEmpty(name)) {
            Intent intent = new Intent();
            intent.putExtra(VALUE_LAT, lat);
            intent.putExtra(VALUE_LNG, lng);
            intent.putExtra(VALUE_NAME, name);
            setResult(RESULT_OK, intent);
        }
        finish();
    }

    public void saveResult(double lat, double lng, String addressName) {
        LogHelper.e("set map ", "" + lat + "|" + lng + "|" + addressName);
        if (getIntent().getBooleanExtra(IM_RESULT, false)) {
            //聊天界面选择地图
            Map.Entry<Double, Double> pointF = bd_encrypt(lat, lng);
            LogHelper.e("encry", " " + pointF.getKey() + "|" + pointF.getValue());
            String url = "http://restapi.amap.com/v3/staticmap?location=" + pointF.getValue() + "," + pointF.getKey() + "&zoom=16&size=300*300&key=8aa78f0b74184f42e6e620866ec13802";
            LogHelper.e("set map ", "" + url);
            Uri uri = Uri.parse(url);
            LocationMessage mMsg = LocationMessage.obtain(lat, lng,
                    addressName, uri);
            MainApplication.getCallback().onSuccess(mMsg);
            MainApplication.setCallback(null);
            finish();
//                           ?location=116.481485,39.990464&zoom=10&size=750*300&markers=mid,,A:116.481485,39.990464&key=ee95e52bf08006f63fd29bcfbcf21df0
        } else {
            Intent intent = new Intent();
            intent.putExtra(VALUE_LAT, lat);
            intent.putExtra(VALUE_LNG, lng);
            intent.putExtra(VALUE_NAME, addressName);

            setResult(RESULT_OK, intent);
        }
        finish();
    }

    final double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

    Map.Entry<Double, Double> bd_encrypt(double gg_lat, double gg_lon) {
        double x = gg_lon, y = gg_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        return new HashMap.SimpleEntry(gg_lat, gg_lon);
    }

    @Override
    public boolean initCloseTopBar() {
        return true;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        return null;
    }
}
